package cn.com.gridinfo.sooc.core.my.order.fragment;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.support.v4.widget.SwipeRefreshLayout;
import android.support.v7.widget.LinearLayoutManager;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

import com.marshalchen.ultimaterecyclerview.UltimateRecyclerView;

import butterknife.ButterKnife;
import butterknife.InjectView;
import cn.com.gridinfo.sooc.R;
import cn.com.gridinfo.sooc.SoocApplication;
import cn.com.gridinfo.sooc.base.BaseSoocFragment;
import cn.com.gridinfo.sooc.core.course.classes.activity.CourseDetailActivity;
import cn.com.gridinfo.sooc.core.course.pay.activity.PayOrderActivity;
import cn.com.gridinfo.sooc.core.my.commen.CodeConst;
import cn.com.gridinfo.sooc.core.my.dao.MyDao;
import cn.com.gridinfo.sooc.core.my.order.MyOrderActivity;
import cn.com.gridinfo.sooc.core.my.order.adapter.OrderAdapter;
import cn.com.gridinfo.sooc.core.my.order.bean.Order;
import cn.com.gridinfo.sooc.utils.MessageUtils;

/**
 * 订单 fragment
 * Created by yingchunli on 2016/8/11.
 */
public class OrderFragment extends BaseSoocFragment {

    View view;//当前界面
    MyDao dao;
    LinearLayoutManager linearLayoutManager;
    String status;//订单状态，0：全部，1：已付款  2：待付款 3：已取消，默认为0
    int pageNo = 1;
    int pageSize = 10;
    @InjectView(R.id.order_list)
    UltimateRecyclerView orderList;
    OrderAdapter adapter;//适配器
    int maxLastPositon;//数据最后位置
    int curPosition;//当前位置

    public static OrderFragment newInstance(String info) {
        Bundle args = new Bundle();
        OrderFragment fragment = new OrderFragment();
        args.putString("info", info);
        fragment.setArguments(args);
        return fragment;
    }

    @Override
    public void setUserVisibleHint(boolean isVisibleToUser) {
        //判断Fragment中的ListView时候存在，判断该Fragment时候已经正在前台显示  通过这两个判断，就可以知道什么时候去加载数据了
        if (isVisibleToUser && isVisible()) {
            initData(); //加载数据的方法
        }
        super.setUserVisibleHint(isVisibleToUser);
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        view = inflater.inflate(R.layout.my_order_fragment, null);
        ButterKnife.inject(this, view);
        dao = new MyDao(this);
        linearLayoutManager = new LinearLayoutManager(getActivity());
        orderList.setLayoutManager(linearLayoutManager);
        status = getArguments().getString("info");
        if (status.equals("2")) {
            status = "0";
        } else if (status.equals("3")) {
            status = "2";
        } else if (status.equals("0")) {
            status = "";
        }
        if (status.equals("")) {
            initData();
        }

        return view;
    }

    /**
     * 初始化列表数据
     */
    void initListView() {
        adapter = new OrderAdapter(dao.getOrderList(), getActivity());
        orderList.setAdapter(adapter);
        orderList.enableLoadmore();
        orderList.setDefaultOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
            @Override
            public void onRefresh() {
                pageNo = 1;//首页
                dao.getMyOrderList(status, pageNo, pageSize, CodeConst.MY_ORDER_LIST_REFRESH);
                linearLayoutManager.scrollToPosition(0);
            }
        });
        orderList.setOnLoadMoreListener(new UltimateRecyclerView.OnLoadMoreListener() {
            @Override
            public void loadMore(final int itemsCount, final int maxLastVisiblePosition) {
                if (itemsCount > (pageSize - 1)) {
                    maxLastPositon = maxLastVisiblePosition;
                    dao.getMyOrderList(status, ++pageNo, pageSize, CodeConst.MY_ORDER_LIST_LOADMORE);
                } else {
                    adapter.loadNoDataView();
                    linearLayoutManager.scrollToPositionWithOffset(maxLastVisiblePosition, -1);
                }
            }
        });
        adapter.setmOnItemClickLitener(new OrderAdapter.OnItemClickListener() {
            @Override
            public void onGoPay(int position, Order order) {
                //去支付页面
                curPosition = position;
                Intent intent = new Intent(getActivity(), PayOrderActivity.class);
                intent.putExtra("kcid", order.getKcid());
                intent.putExtra("kcmc", order.getKcmc());
                intent.putExtra("price", order.getPrice());
                intent.putExtra("kcfm", order.getKcfm());
                intent.putExtra("kcls", order.getKcjs());
                intent.putExtra("from","orders");//标记来源
                SoocApplication.orderId = order.getOrderid();
                startActivityForResult(intent, CodeConst.INTENT_LOOKCOURSE);
            }

            @Override
            public void lookCourse(int position, Order order) {
                //查看课程
                curPosition = position;
                Intent intent = new Intent(getActivity(), CourseDetailActivity.class);
                intent.putExtra("kcid", order.getKcid());
                intent.putExtra("kcfm", order.getKcfm());
                startActivityForResult(intent, CodeConst.INTENT_LOOKCOURSE);
            }

            @Override
            public void cancelOrder(int position, Order order) {
                curPosition = position;
                //取消订单
                dao.cancelCourse(order.getOrderid());
            }
        });
    }

    @Override
    public void onRequestSuccess(int requestCode) {
        try {
            if (dao.status.equals("0")) {
                switch (requestCode) {
                    case CodeConst.MY_ORDER_LIST_FIRST:
                        //我的订单 首次请求
                        if (dao.getOrderList().size() < 1 && status.equals("")) {
                            //无数据时，显示空白页
                            MyOrderActivity.tabLayout.setVisibility(View.GONE);
                            MyOrderActivity.blankView.setVisibility(View.VISIBLE);
                        } else {
                            MyOrderActivity.tabLayout.setVisibility(View.VISIBLE);
                            initListView();
                        }
                        break;

                    case CodeConst.MY_ORDER_LIST_LOADMORE:
                        //我的订单 加载请求
                        if (dao.getScCourseList() != null && !dao.getScCourseList().isEmpty()) {
                            //加载更多
                            adapter.loadmore(dao.getOrderList());
                        } else {
                            //无数据则不显示下一页
                            adapter.loadNoDataView();
                            linearLayoutManager.scrollToPositionWithOffset(maxLastPositon, -1);
                        }
                        break;

                    case CodeConst.MY_ORDER_LIST_REFRESH:
                        //我的订单 刷新请求
                        orderList.setRefreshing(false);
                        if (dao.getOrderList() != null && !dao.getOrderList().isEmpty()) {
                            orderList.hideEmptyView();
                        } else {
                            //无数据处理
                            orderList.showEmptyView();
                        }
                        //刷新数据
                        adapter.refresh(dao.getOrderList());
                        if (dao.getOrderList().size() > (pageSize - 1))
                            //数据大于每页显示的条数
                            adapter.loadMoreDataView();
                        else {
                            //数据小于当前页的话则不显示加载更多
                            adapter.loadNoDataView();
                            linearLayoutManager.scrollToPositionWithOffset(maxLastPositon, -1);
                            linearLayoutManager.scrollToPosition(maxLastPositon);
                        }
                        break;

                    case CodeConst.ODRER_CANCELORDER:
                        //取消订单成功
                        MessageUtils.showRightImageShortToast(getActivity(), "取消订单成功");
                        //重新请求数据
                        pageNo = 1;
                        dao.getMyOrderList(status, pageNo, pageSize, CodeConst.MY_ORDER_LIST_REFRESH);
                        linearLayoutManager.scrollToPosition(0);
                        break;
                }
            } else {
                MessageUtils.showImageShortToast(getActivity(), dao.statusCode);
            }
        } catch (Exception e) {
            MessageUtils.showImageShortToast(getActivity(), "数据请求异常");
        }
    }

    void initData() {
        if (adapter == null) {
            //发送请求  获取列表
            dao.getMyOrderList(status, pageNo, pageSize, CodeConst.MY_ORDER_LIST_FIRST);
        } else {
            pageNo = 1;//首页
            dao.getMyOrderList(status, pageNo, pageSize, CodeConst.MY_ORDER_LIST_REFRESH);
            linearLayoutManager.scrollToPosition(0);
        }
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode != Activity.RESULT_OK) return;
        switch (requestCode) {
            case CodeConst.INTENT_GOPAY://去支付
                break;
            case CodeConst.INTENT_LOOKCOURSE://查看课程
                break;
        }
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        ButterKnife.reset(this);
    }
}
